/*
与防抖函数一样，
节流也是常见的项目交互优化方式，
主要是指在事件被触发后，
在规定时间内无论再怎么触发只会调用一次函数，
直到时间结束。
节流函数根据业务需求传入等待时间，
不传默认设置2s
*/
import type { Directive, DirectiveBinding } from 'vue';
interface ElType extends HTMLElement {
  __handleClick__: (event: MouseEvent) => any;
  disabled: boolean;
}
const throttle: Directive = {
  mounted(el: ElType, binding: DirectiveBinding) {
    if (typeof binding.value !== 'function') {
      return;
    }
    const duration = binding.arg ? parseInt(binding.arg) : 2000;
    let timer: any = null;
    el.__handleClick__ = (event: MouseEvent) => {
      if (timer) {
        clearTimeout(timer);
      }
      if (!el.disabled) {
        el.disabled = true;
        el.classList.add('is-loading');
        binding.value(event);
        timer = setTimeout(() => {
          el.disabled = false;
          el.classList.remove('is-loading');
        }, duration);
      }
    };
    el.addEventListener('click', el.__handleClick__);
  },
  beforeUnmount(el: ElType) {
    el.removeEventListener('click', el.__handleClick__);
  }
};
export default throttle;
